package com.ycsd.invest.order.business.workflowplugin;

import com.alibaba.fastjson.JSONObject;
import kd.bos.coderule.api.CodeRuleInfo;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.workflow.EventServiceHelper;
import kd.bos.servicehelper.workflow.MessageCenterServiceHelper;
import kd.bos.workflow.api.AgentExecution;
import kd.bos.workflow.api.AgentTask;
import kd.bos.workflow.api.WorkflowElement;
import kd.bos.workflow.component.approvalrecord.ApprovalAttachmentInfo;
import kd.bos.workflow.component.approvalrecord.CustomizeLink;
import kd.bos.workflow.component.approvalrecord.IApprovalRecordItem;
import kd.bos.workflow.engine.extitf.IWorkflowPlugin;
import kd.bos.workflow.engine.msg.info.MessageInfo;

import java.util.*;

/**
 * 流程插件
 */
public class OrderInfoFlow implements IWorkflowPlugin {

    @Override
    public List<Long> calcUserIds(AgentExecution execution) {
        String BusinessKey = execution.getBusinessKey();//单据的BusinessKey(业务ID)
        List<Long> currentApprover = execution.getCurrentApprover();//获取当前节点的审批人
        WorkflowElement<?> flowElement = execution.getCurrentFlowElement();//当前节点
        String id = flowElement.getId();//当前流程节点ID
        String name = flowElement.getName();//当前节点名称
        String number = flowElement.getNumber();//当前节点id
        String entityNumber = execution.getEntityNumber();//单据实体编码
        Long processDefinitionId = execution.getProcessDefinitionId();//获取流程定义ID
        Long processInstanceId = execution.getProcessInstanceId();//获取流程实例ID
        Long startUserId = execution.getStartUserId();//获取流程发起人

        Object variable = execution.getVariable("bizApplier");//获取流程变量，参数为String,此处为流程动态配置方案中"名称"的值,得到的是“默认值”的值
        Object aaa = execution.getVariable("aaa");//获取流程变量，参数为String,此处为流程动态配置方案中"名称"的值,得到的是“默认值”的值
        DynamicObject transientBill = execution.getTransientBill();
        String billno = transientBill.getString("billno");


        //下面是自定义业务 把创建人设置为节点参与人
        currentApprover.add(startUserId);

        List<Long> userIds = new ArrayList<>();
        List<String> numberList = new ArrayList<>();
        numberList.add("ID-017004");
        numberList.add("ID-030013");
        numberList.add("ID-002007");
        numberList.add("ID-019001");
        QFilter filter = new QFilter("number", QCP.in, numberList);
        DynamicObjectCollection bosUser = QueryServiceHelper.query("bos_user", "id,name,number", new QFilter[]{filter});
        for (DynamicObject dynamicObject : bosUser) {
            userIds.add(dynamicObject.getLong("id"));
        }
        return userIds;//返回值为 List<Long> 类型的数据。返回内容为参与人的id
    }

    @Override
    public IApprovalRecordItem formatFlowRecord(IApprovalRecordItem item) {
        //节点记录格式化
        String activityId = item.getActivityId();//获取当前流程节点id
        String activityName = item.getActivityName();//获取当前流程节点名称
        String assignee = item.getAssignee();//获取审批人姓名
        List<ApprovalAttachmentInfo> attachments = item.getAttachments();//获取附件
        String avatar = item.getAvatar();//获取头像地址
        String decisionType = item.getDecisionType();//获取决策项类型
        String message = item.getMessage();//获取审批意见
        String openId = item.getOpenId();//获取openId
        Long ownerId = item.getOwnerId();//获取当前处理人的id
        String ownerName = item.getOwnerName();//获取当前处理人的姓名
        String result = item.getResult();//获取处理结果
        String state = item.getState();//获取单据状态
        String subactivityname = item.getSubactivityname();//获取
        String taskId = item.getTaskId();//获取任务ID
        String time = item.getTime();//获取处理时间
        Long userId = item.getUserId();//获取节点处理人id
        String userStr = item.getUserStr();//获取节点处理人id


        CustomizeLink customizeLink = new CustomizeLink();
        customizeLink.setUrl("https://www.baidu.com/");
        customizeLink.setText("百度一下，你就知道");
        item.setActivityName("获取当前流程节点名称1111111");
        item.setLinks(Collections.singletonList(customizeLink));
        return item;
    }

    @Override
    public void notify(AgentExecution execution) {
        IWorkflowPlugin.super.notify(execution);
        // 流程结束的通知、数据下推（自动发起流程）、投票结果的计算

        // 单据编码
        String entityNumber = execution.getEntityNumber();
        // PK
        String businessKey = execution.getBusinessKey();
        DynamicObject bill = BusinessDataServiceHelper.loadSingle(businessKey, entityNumber);

        //流程结束通知
//        MessageInfo message = new MessageInfo();
//        message.setTitle("我要发一个消息。。。。。。。。。。。。。");
//        message.setContent("我要发一个消息。。。。。。。。。。。。的内容警告");
//        message.setUserIds(Collections.singletonList(execution.getStartUserId()));
//        message.setEntityNumber(null);
//        message.setBizDataId(null);
//        message.setOperation("modify");
//        message.setSenderId(0L);
//        message.setSendTime(new Date());
//        message.setSource("警告警告警告警告1");
//        message.setType(MessageInfo.TYPE_WARNING);
//        message.setTag("警告警告警告警告");
//        message.setContentUrl(null);
//        MessageCenterServiceHelper.sendMessage(message);

        //自动发起流程(创建一个单据 触发操作)
//        DynamicObject studentBill = BusinessDataServiceHelper.newDynamicObject("ycsd_order_info");
//        studentBill.set("total_amount","7");
//        studentBill.set("billStatus","A");
//        CodeRuleInfo codeRule = CodeRuleServiceHelper.getCodeRule(studentBill.getDataEntityType().getName(), studentBill, String.valueOf(RequestContext.get().getOrgId()));
//        String number = CodeRuleServiceHelper.getNumber(codeRule, studentBill);
//        studentBill.set("billNo",number);
//
//        OperationResult submitResult = OperationServiceHelper.executeOperate("submit", entityNumber, new DynamicObject[]{
//                studentBill
//        }, OperateOption.create());
//
//        System.out.println(submitResult);

    }
}
